import json
import re

from django.views import View
from django.http import JsonResponse
from django.contrib.auth import login, authenticate, logout
from django.core.mail import send_mail

from utils.views import LoginRequiredJSONMixin
from apps.users.models import User, Address
from apps.users.utils import generic_email_verify_token, check_verify_token
from celery_tasks.email.tasks import celery_send_email


# Create your views here.

class UsernameCountView(View):

    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        return JsonResponse({"code": 0, "count": count, "errmsg": "ok"})


class RegisterView(View):

    def post(self, request):

        body_bytes = request.body
        body_str = body_bytes.decode()
        body_dict = json.loads(body_str)

        username = body_dict.get("username")
        password = body_dict.get("password")
        password2 = body_dict.get("password2")
        mobile = body_dict.get("mobile")
        allow = body_dict.get("allow")

        if not all([username, password, password2, mobile, allow]):
            return JsonResponse({"code": 400, "errmsg": "参数错误"})

        if not re.match("[a-zA-Z_-]{5,20}", username):
            return JsonResponse({"code": 400, "errmsg": "用户名错误"})

        if password != password2:
            return JsonResponse({"code": 400, "errmsg": "密码不一致"})

        if not re.match("1[345789]\d{9}", mobile):
            return JsonResponse({"code": 400, "errmsg": "电话号码错误"})

        if allow != True:
            return JsonResponse({"code": 400, "errmsg": "未同意协议"})

        user = User.objects.create_user(username=username,
                                        password=password,
                                        mobile=mobile)

        login(request, user)

        return JsonResponse({"code": 0, "errmsg": "注册完成"})


class LoginView(View):

    def post(self, request):

        data = json.loads(request.body.decode())

        username = data.get('username')
        password = data.get('password')
        remembered = data.get('remembered')

        if re.match('1[3-9]\d{9}', username):
            User.USERNAME_FIELD = 'mobile'

        else:
            User.USERNAME_FIELD = 'username'

        if not all([username, password]):
            return JsonResponse({"code": 400, "errmsg": "参数不全"})

        # 若用户名和密码正确则返回user 反之则返回None
        user = authenticate(username=username, password=password)

        if user is None:
            return JsonResponse({"code": 400, "errmsg": "账号或密码错误"})

        # session
        login(request, user)

        if remembered:
            # 记住登录
            request.session.set_expiry(None)
        else:
            # 浏览器关闭 过期
            request.session.set_expiry(0)

        response = JsonResponse({"code": 200, "errmsg": "登录完成"})
        # 首页显示用户
        response.set_cookie('username', username)
        return response


class LogoutView(View):
    def get(self, request):
        logout(request)

        response = JsonResponse({"code": 0, "errmsg": "ok"})

        response.delete_cookie('username')

        return response


class CenterView(LoginRequiredJSONMixin, View):

    def get(self, request):
        info_data = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active,
        }

        return JsonResponse({"code": 0, "errmsg": "ok", "info_data": info_data})


class EmailView(LoginRequiredJSONMixin, View):

    def put(self, request):
        data = json.loads(request.body.decode())
        email = data.get('email')

        user = request.user
        user.email = email
        user.save()

        token = generic_email_verify_token(request.user.id)

        verify_url = "http://www.meiduo.site:8080/success_verify_email.html?token=%s" % token
        # 4.2 组织我们的激活邮件
        html_message = '<p>尊敬的用户您好！</p>' \
                       '<p>感谢您使用美多商城。</p>' \
                       '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)
        subject = '美多商城激活邮件'
        message = ""
        from_email = '美多商城<qi_rui_hua@163.com>'
        recipient_list = ['qi_rui_hua@126.com', 'qi_rui_hua@163.com']
        # subject 主题
        # message 内容
        # from_email 发件人
        # recipient_list 收件人列表
        # send_mail(subject='凯',
        #           message='俺是你爹哦',
        #           from_email='x961313969@163.com',
        #           recipient_list=['x961313969@163.com'],
        #           html_message="点击<a href='http://www.baidu.com/token=%s'>激活</a>" % token)
        celery_send_email.delay(
            subject=subject,
            message=message,
            from_email=from_email,
            recipient_list=recipient_list,
            html_message=html_message
        )

        return JsonResponse({'code': 0, 'errmsg': 'ok'})


class EmailVerifyView(View):

    def put(self, request):
        params = request.GET
        token = params.get('token')

        if token is None:
            return JsonResponse({'code': 400, 'errmsg': '参数缺失'})

        user_id = check_verify_token(token)
        if user_id is None:
            return JsonResponse({'code': 400, 'errmsg': '参数错误'})

        user = User.objects.get(id=user_id)
        user.email_active = True
        user.save()

        return JsonResponse({'code': 0, 'errmsg': 'ok'})


class AddressCreateView(LoginRequiredJSONMixin, View):

    def post(self, request):
        data = json.loads(request.body.decode())

        receiver = data.get('receiver')
        province_id = data.get('province_id')
        city_id = data.get('city_id')
        district_id = data.get('district_id')
        place = data.get('place')
        mobile = data.get('mobile')
        tel = data.get('tel')
        email = data.get('email')
        user = request.user

        address = Address.objects.create(
            user=user,
            title=receiver,
            receiver=receiver,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            place=place,
            mobile=mobile,
            tel=tel,
            email=email
        )

        address_dict = {
            'id': address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'address': address_dict})


class AddressView(LoginRequiredJSONMixin, View):

    def get(self, request):
        user = request.user

        addresses = Address.objects.filter(user=user, is_deleted=False)

        address_list = []
        for address in addresses:
            address_list.append({
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            })
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'addresses': address_list})
